package com.hertz.iris.view;

import java.io.IOException;
import java.util.List;

import javax.inject.Inject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
import com.github.kevinsawicki.wishlist.SingleTypeAdapter;
import com.github.kevinsawicki.wishlist.Toaster;
import com.hertz.iris.Injector;
import com.hertz.iris.IrisApplication;
import com.hertz.iris.R;
import com.hertz.iris.core.DBService;
import com.hertz.iris.core.MatchAlarmService;
import com.hertz.iris.pojo.MatchAlarm;
import com.hertz.iris.pojo.MatchNba;
import com.hertz.iris.util.BundleKeys;
import com.hertz.iris.util.Constants;
import com.hertz.iris.util.DateUtil;
import com.hertz.iris.view.matchalarm.MatchAlarmActivity;
/**
 * Adapter to display a list of traffic items
 */
public class MatchsListAdapter extends SingleTypeAdapter<MatchNba> {
	
	@Inject MatchAlarmService matchAlarmService;
	private Activity activity;
	
    /**
     * @param inflater
     * @param items
     */
    public MatchsListAdapter(Activity activity, List<MatchNba> items) {
        super(activity, R.layout.match_list_item);
        this.activity = activity;
        setItems(items);
        Injector.inject(this);
    }


    @Override
    public long getItemId(final int position) {
        final String id = getItem(position).getId().toString();
        return !TextUtils.isEmpty(id) ? id.hashCode() : super
                .getItemId(position);
    }

    @Override
    protected int[] getChildViewIds() {
		return new int[] { R.id.host_name, R.id.guest_name,
				R.id.match_status_text, R.id.match_time_text, R.id.host_score,
				R.id.guest_score, R.id.shortcut_set_alarm, R.id.match_time_ll };
    }
    
    @Override
	public View getView(final int position, View convertView, ViewGroup parent) {
    	final View view = super.getView(position, convertView, parent);
    	
    	LinearLayout matchTimeLL = (LinearLayout)view.findViewById(R.id.match_time_ll);
    	View starView = view.findViewById(R.id.shortcut_set_alarm);
    	
    	final MatchNba matchNba = getItem(position);
    	
    	matchTimeLL.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				MatchNba mn = getItem(position);
				Intent intent = new Intent(v.getContext(), MatchAlarmActivity.class);
				intent.putExtra(BundleKeys.MatchAlarmBundleKeys.MATCH_KEY, matchNba);
				MatchAlarm ma = DBService.getInstance().loadMatchAlarmByMid(getItem(position).getId());
				intent.putExtra(BundleKeys.MatchAlarmBundleKeys.MATCH_ALARM_KEY, ma);
				v.getContext().startActivity(intent);
			}
		});
    	
    	starView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				setCurrentView(view);
				v.setEnabled(false);
				Runnable runnable = new PostMatchAalarmThread(matchNba,position);
				new Thread(runnable).start();
			}
		});
    	
    	return view;
    }

    @Override
    protected void update(int position, MatchNba matchNba) {
    	setText(0,matchNba.getHostTeam().getAlias());
    	setText(1,matchNba.getGuestTeam().getAlias());
    	setText(2,matchNba.getStatus());
    	setText(3,matchNba.getMatchTime());
    	setText(4,matchNba.getHostScore().toString());
    	setText(5,matchNba.getGuestScore().toString());
    	TextView tv = updater.textView(6);
    	tv.setTypeface(IrisApplication.getInstance().getTypeface());
    	if(matchNba.isSubscribe()){
    		String star = activity.getResources().getString(R.string.icon_star);
    		tv.setText(star);
    		tv.setTextColor(0xb0F1C40F);
    	}else{
    		String emptyStar = activity.getResources().getString(R.string.icon_star_empty);
    		tv.setText(emptyStar);
    		tv.setTextColor(0xff000000);
    	}
    	
    	View v = updater.view(7);
    	if(matchNba.getPeriod() != 0){
    		v.setEnabled(false);
    		tv.setEnabled(false);
    		v.setBackgroundResource(R.color.normal_disable);
    	}else{
    		v.setEnabled(true);
    		tv.setEnabled(true);
    		v.setBackgroundResource(R.drawable.bbuton_info);
    	}
    }
    
    private Handler mHandler = new Handler(){  
        
        public void handleMessage(Message msg) {  
        	Bundle b = msg.getData();
            switch (msg.what) {  
            case 1:  
            	Toaster.showShort(activity, Constants.ToastMessage.SHORTCUT_SET_ALARM_SUCCESS);
            	update(b.getInt("position"),(MatchNba)b.getSerializable("matchNba"));
                break;
            case 2:  
            	Toaster.showShort(activity, Constants.ToastMessage.SHORTCUT_SET_ALARM_CANCEL_SUCCESS);
            	update(b.getInt("position"),(MatchNba)b.getSerializable("matchNba"));
                break;
            case -1:  
            	Toaster.showShort(activity, Constants.ToastMessage.SHORTCUT_SET_ALARM_ERROR);
                break;
            case -2:  
            	Toaster.showShort(activity, Constants.ToastMessage.SHORTCUT_SET_ALARM_CANCEL_ERROR);
                break;
            case 0:
            	Toaster.showShort(activity, Constants.ToastMessage.OP_ERROR);
            }  
        };  
    };  
	
    private class PostMatchAalarmThread implements Runnable{  
    	private MatchNba matchNba;
    	private int position;
    	public PostMatchAalarmThread(MatchNba matchNba,int position){
    		this.matchNba = matchNba;
    		this.position = position;
    	}
        @Override  
        public void run() {  
              
            Message message = new Message(); 
            message.what = 0;
            try {
            	MatchAlarm matchAlarm = matchAlarmService.getMatchAlarmFromLocal(matchNba.getId());
            	if(matchAlarm == null){//create
            		matchAlarm = new MatchAlarm();
//    				matchAlarm.setUid(Constants.DEFAULT_UID);
    				matchAlarm.setRingName("");
    				matchAlarm.setWave(Constants.MATCH_ALARM.DEFAULT_WAVE);
    				matchAlarm.setEveryQuarter(Constants.MATCH_ALARM.DEFAULT_EVERY_QUARTER);
    				matchAlarm.setVolume(Constants.MATCH_ALARM.DEFAULT_VALUME);
    				matchAlarm.setAgain(Constants.MATCH_ALARM.DEFAULT_AGAIN);
    				matchAlarm.setMid(matchNba.getId());
    				matchAlarm.setPeriod(Constants.MATCH_ALARM.DEFAULT_PERIOD);
    				matchAlarm.setRemain(Constants.MATCH_ALARM.DEFAULT_REMAIN);
    				matchAlarm.setScoreDiff(Constants.MATCH_ALARM.DEFAULT_SCORE_DIFF);
    				matchAlarm.setStatus(Constants.MATCH_ALARM.DEFAULT_SATAUS);
    				matchAlarm.setUtime(System.currentTimeMillis());
    				String matchTimeStr = matchNba.getMatchDay() + " " + matchNba.getMatchTime();
    				matchAlarm.setMatchTime(DateUtil.string2Time(matchTimeStr, DateUtil.YMD_HM));
    				//save or update
    				matchAlarm.setCtime(System.currentTimeMillis());
    				if(matchAlarmService.saveOrUpdateMatchAlarm(matchAlarm, activity)){
    					matchNba.setSubscribe(true);
        				message.what = 1;
    				}else{
    					message.what = -1;
    				}
            	}else{//cancel
            		if(matchAlarmService.cancelMatchAlarm(matchAlarm, activity)){
            			matchNba.setSubscribe(false);
                		message.what = 2;
            		}else{
            			message.what = -2;
            		}
            		
            	}
            	Bundle b = new Bundle();
            	b.putSerializable("matchNba", matchNba);
            	b.putInt("position", position);
            	message.setData(b);
			} catch (HttpRequestException hre){
				hre.printStackTrace();
			}catch (IOException ioe){
				ioe.printStackTrace();
			} catch (Exception e){
				e.printStackTrace();
			}
            MatchsListAdapter.this.mHandler.sendMessage(message);
        }     
    }
}
